'use strict';

const semver = require('semver');
const axios = require('axios');
const urlJoin = require('url-join');


function getNpmInfo(npmName, registry) {
    if(!npmName) return null;
    const registryUrl = registry ? registry : getDefaultRegistry();
    return axios.get(urlJoin(registryUrl,npmName)).then(respose => {
        if(respose.status === 200) {
            return respose.data
        }else{
            return null;
        }
    })
}

function getDefaultRegistry(isOrgin = false) {
    return isOrgin ? 'https://registry.npmjs.org' : 'https://registry.npmmirror.com';
}

async function getNpmVersions(npmName,registry){
    const { versions } = await getNpmInfo(npmName,registry);
    if(versions){
        return Object.keys(versions);
    }else{
        return []
    }
}

async function getSemverNpmVesion(npmName,currentVersion,registry){
    const versions = await getNpmVersions(npmName,registry);
    if(versions && versions.length > 0){
        const newVersions =  versions
        .filter(version => semver.gt(version,currentVersion))
        .sort((a,b) => semver.compare(b,a))
        if(newVersions && newVersions.length > 0){
            return newVersions[0];
        }
    }
    return null;
}


async function getLatestNpmVersion(npmName,registry){
    const versions = await getNpmVersions(npmName,registry);
    if(versions && versions.length > 0){
        return versions.sort((a,b) => semver.compare(b,a))[0]
    }
    return null;

}


module.exports = {
    getNpmInfo,
    getNpmVersions,
    getLatestNpmVersion,
    getDefaultRegistry,
    getSemverNpmVesion
};
